package com.weido.registry;

import com.weido.rpc.Protocol.InvokerProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class RegistryHandler extends ChannelInboundHandlerAdapter {

    //key:对外提供服务接口的完整路径，
    public static ConcurrentHashMap<String, Object> registryMap = new ConcurrentHashMap<>();
    //保存所有相关的服务类
    private List<String> className = new ArrayList<>();


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Object result = new Object();
        InvokerProtocol request = (InvokerProtocol) msg;
        // rpc.api.HelloService
        if (registryMap.containsKey(request.getClassName())) {
            Object clazz = registryMap.get(request.getClassName());
            Method method = clazz.getClass().getMethod(request.getMethodName(), request.getParams());
            result = method.invoke(clazz, request.getValues());
        }
        ctx.write(result);
        ctx.flush();
        ctx.close();
    }

    public RegistryHandler() {
        //发现服务
        scannerClass("com.weido.Service");
        //注册服务
        doRegister();
    }

    // 扫描文件
    public void scannerClass(String packageName) {
        URL url = this.getClass().getClassLoader().getResource(packageName.replaceAll("\\.", "/"));
        String path=null;
        try {
            path = URLDecoder.decode(url.getFile(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        File dir = new File(path);
        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                scannerClass(packageName + "." + file.getName());
            } else {
                className.add(packageName + "." + file.getName().replace(".class", "").trim());
            }
        }
    }

    public void doRegister() {
        if (className.size() == 0) {
            return;
        }
        for (String classNam : className) {
            try {
                Class<?> clazz = Class.forName(classNam);
                Class<?> i = clazz.getInterfaces()[0];
                if (i == null) {
                    continue;
                }
                registryMap.put(i.getName(), clazz.newInstance());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        String packageName= "com.weido.Service";
        String uri=   packageName.replaceAll("\\.", "/");
        System.out.println(uri);
    }
}
